package com.gisuni.sddc.platformManager.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import com.gisuni.sddc.platformManager.dao.UserDao;
import com.gisuni.sddc.platformManager.model.Organization;
import com.gisuni.sddc.platformManager.model.Response;
import com.gisuni.sddc.platformManager.model.Tree;
import com.gisuni.sddc.platformManager.model.UserInfo;
import com.gisuni.sddc.util.MD5Util;
import com.gisuni.sddc.util.StringUtil;

@IocBean
public class UserService {

	private Log log = Logs.getLog(UserService.class);
	@Inject 
	private UserDao  userDao;

	


	/**
	 * 查询数据
	 * 
	 * @param 
	 * @return
	 */
	public Response queryBaseUserAll(int from,int to,String name,String organizationId) {
		Response response = new Response();
		response.setSuccess(false);
		String Result=null;
		StringBuffer resultStr=null;
		StringBuffer selectstr=null;
		StringBuffer rowstr=null;
		String andSelect = "";
		try {
			selectstr = new StringBuffer();
			rowstr = new StringBuffer();
			resultStr = new StringBuffer();
			
			/**
               select t.*,t3.roleIds,t3.rolenames,t4.ORGANIZATION_COMPANY_ID,t4.ORGANIZATION_BUSINESS_ID,t4.ORGANIZATION_DEVELOP_ID,
               t4.companyName,t4.busiName,t4.devName,t4.companyName||t4.busiName||t4.devName orgFullName from user_info t 
               left join (select t1.user_id,listagg( t2.role_name, ',' ) within group ( order by t2.role_name ) as rolenames 
               ,listagg( t2.role_id, ',' ) within group ( order by t2.role_id ) as roleIds
               from user_r_role t1 , role_info t2 where t1.role_id = t2.role_id group by t1.user_id) t3 on t.user_id = t3.user_id 
               left join SDDCGISPLATFORM.v_user_organization_detail t4 on t.user_id = t4.USER_ID
			 */

			rowstr.append("  select count(1) cous from   (");
			
			resultStr.append("  select * from  (");
			
//			selectstr.append("  select t.*,t3.rolenames,t3.roleids,rownum rowno from user_info t ");
//			selectstr.append(" left join (select t1.user_id,listagg( t2.role_name, ',' ) within group ( order by t2.role_name ) as rolenames ");
//			selectstr.append(" ,listagg( t2.role_id, ',' ) within group ( order by t2.role_id ) as roleIds ");
//			selectstr.append(" from user_r_role t1 , role_info t2 where t1.role_id = t2.role_id group by t1.user_id ) t3 on t.user_id = t3.user_id where 1=1 ");
			selectstr.append("  select t.*,t3.roleIds,t3.rolenames,t4.ORGANIZATION_COMPANY_ID,t4.ORGANIZATION_BUSINESS_ID,t4.ORGANIZATION_DEVELOP_ID, ");
			selectstr.append("   t4.companyName,t4.busiName,t4.devName,t4.companyName||t4.busiName||t4.devName orgFullName,rownum rowno from SDDCGISPLATFORM.user_info t  ");
			selectstr.append("   left join (select t1.user_id,listagg( t2.role_name, ',' ) within group ( order by t2.role_name ) as rolenames  ");
			selectstr.append("   ,listagg( t2.role_id, ',' ) within group ( order by t2.role_id ) as roleIds ");
			selectstr.append("   from SDDCGISPLATFORM.user_r_role t1 , role_info t2 where t1.role_id = t2.role_id group by t1.user_id) t3 on t.user_id = t3.user_id  ");
			selectstr.append("   left join SDDCGISPLATFORM.v_user_organization_detail t4 on t.user_id = t4.USER_ID where 1=1 ");
			
			
			
			//名称
			if(!StringUtil.isNullOrEmpty(name)){
				selectstr.append(" and (t.user_name like '%"+name+"%' or t.displayname like '%"+name+"%')");
			}
			
			//组织
			if(!StringUtil.isNullOrEmpty(organizationId)){
				selectstr.append(" and (t4.ORGANIZATION_COMPANY_ID='"+organizationId+"' or t4.ORGANIZATION_BUSINESS_ID='"+organizationId+"' or t4.ORGANIZATION_DEVELOP_ID='"+organizationId+"' )");
			}
			resultStr.append(selectstr.toString());
			resultStr.append(" and rownum<"+to+") where rowno>"+from);
			
			rowstr.append(selectstr.toString()+") ");
			//TODO
//			resultStr = new StringBuffer("select t.* from SDDCGISPLATFORM.temp_user_info_detail t");
			Result = userDao.querySQL(resultStr.toString());
			
			response.setSuccess(true);
			
			//结果集  这里得到的Result会多了个{}
			response.setResult( new JSONArray(Result.replace(",{}", "")));
			
			//条数
			Result = userDao.querySQL(rowstr.toString());
			JSONArray resultJsonArr = new JSONArray(Result);
			if (resultJsonArr != null && resultJsonArr.length() > 0) {

				for (int i = 0; i < resultJsonArr.length(); i++) {
					JSONObject ret = (JSONObject) resultJsonArr.get(i);
					Iterator iterator = ret.keys();
					while (iterator.hasNext()) {
						String key = (String) iterator.next();
						String value = (String) ret.get(key);
						if("COUS".equals(key)){
							response.setTotal(Integer.parseInt(value));//总条数
						}
					}
				}
			}
			
			
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return response;
		}
	}




	public UserInfo findUserInfoById(String id) {
		// TODO Auto-generated method stub
		UserInfo userInfo = null ;
		StringBuffer selectstr=null;
		if(!StringUtil.isNullOrEmpty(id)){
			//TODO
			selectstr=new StringBuffer();
			selectstr.append("  select t.*,t3.roleIds,t3.rolenames,t4.ORGANIZATION_COMPANY_ID,t4.ORGANIZATION_BUSINESS_ID,t4.ORGANIZATION_DEVELOP_ID, ");
			selectstr.append("   t4.companyName,t4.busiName,t4.devName,t4.companyName||t4.busiName||t4.devName orgFullName,rownum rowno from SDDCGISPLATFORM.user_info t  ");
			selectstr.append("   left join (select t1.user_id,listagg( t2.role_name, ',' ) within group ( order by t2.role_name ) as rolenames  ");
			selectstr.append("   ,listagg( t2.role_id, ',' ) within group ( order by t2.role_id ) as roleIds ");
			selectstr.append("   from SDDCGISPLATFORM.user_r_role t1 , role_info t2 where t1.role_id = t2.role_id group by t1.user_id) t3 on t.user_id = t3.user_id  ");
			selectstr.append("   left join SDDCGISPLATFORM.v_user_organization_detail t4 on t.user_id = t4.USER_ID ");
			selectstr.append("  where T.user_id='"+id+"'");;
			//TODO
//			selectstr = new StringBuffer("SELECT * from SDDCGISPLATFORM.finduserinfobyid t where t.user_id='"+id+"'");
			userInfo = userDao.findUserInfoById(selectstr.toString());
		}
		return userInfo;
	}



	//添加
	public Response addUser(HttpServletRequest request) {
		 Response response = new Response();
		 response.setSuccess(false);
		 UserInfo userInfo = new UserInfo() ;
		 String userName = request.getParameter("loginname");
		 String displayName = request.getParameter("name");
		 String password = request.getParameter("password");
		 String userType = request.getParameter("usertype");
		 String status = request.getParameter("status");
		 String phone = request.getParameter("phone");
		 String sex = request.getParameter("sex");
		 String organizationIds = request.getParameter("organizationId");
//		 String roles = request.getParameter("roleIds");
		 String[] rolesArr = request.getParameterValues("roleIds");
		 if(status==null){
			 status="1";
		 }
		 if(sex==null){
			 sex="1";
		 }
		 //TODO 登录名重复提示 失败的提示
		 if(StringUtil.isNullOrEmpty(userName)||StringUtil.isNullOrEmpty(password)){
			 response.setMsg("登录名与密码不能为空");
			 return response;
		 }
		 
		 boolean checkflag = userDao.checkUserName(userName);
		 if(!checkflag){
			 response.setMsg("登录名已存在");
			 return response;
		 }
			 
		 StringBuffer sqlSbf = new StringBuffer();
		 String id  = UUID.randomUUID().toString().replaceAll("-", "") ;
		 String pwd = MD5Util.str2MD5(password);
		 sqlSbf.append(" insert into SDDCGISPLATFORM.User_Info(USER_ID,USER_NAME,USER_PASSWORD,DISPLAYNAME,USER_TYPE,STATUS,TELEPHONE,SEX) ");
		 sqlSbf.append(" values('"+id+"','"+userName+"','"+pwd+"','"+displayName+"','"+userType+"','"+status+"','"+phone+"','"+sex+"')");
		 //新增用户
		 boolean flag = userDao.executeSql(sqlSbf.toString());
		 if(!flag){
			 response.setMsg("保存用户失败");
			 return response;
		 }
		 //用户-组织关系
		 flag= excUserOrg(id,organizationIds,"add");
		 if(!flag){
			 response.setMsg("保存用户-组织失败");
			 return response;
		 }
		 //用户-角色关系
		 flag= excUserOrle(id,rolesArr,"add");
		 if(!flag){
			 response.setMsg("保存用户-角色失败");
			 return response;
		 }
		 response.setMsg("操作成功");
		 response.setSuccess(true);
		return response;
	}

	//修改
	public Response updateUser(HttpServletRequest request) {
		 Response response = new Response();
		 response.setSuccess(false);
		 UserInfo userInfo = new UserInfo() ;
		 String userName = request.getParameter("loginname");
		 String displayName = request.getParameter("name");
		 String password = request.getParameter("password");
		 String userType = request.getParameter("userType");
		 String status = request.getParameter("status");
		  
		 String phone = request.getParameter("phone");
		 String sex = request.getParameter("sex");
		 
		 String organizationIds = request.getParameter("organizationId");
		 String userId = request.getParameter("id");
		 String[] rolesArr = request.getParameterValues("roleIds");
		 if(status==null){
			 status="1";
		 }
		 if(sex==null){
			 sex="1";
		 }
		 // 
		 if(StringUtil.isNullOrEmpty(userName) ){
			 response.setMsg("登录名不能为空");
			 return response;
		 }
		 
//		 boolean checkflag = userDao.checkUserName(userName);
//		 if(!checkflag){
//			 response.setMsg("登录名已存在");
//			 return response;
//		 }
		 
		 //密码为空时不做修改
		 String pwdUpdate = "";
		 if(!StringUtil.isNullOrEmpty(password) ){
			 
			 pwdUpdate = ",USER_PASSWORD='"+MD5Util.str2MD5(password)+"'";
			 
		 }
		  
		 StringBuffer sqlSbf = new StringBuffer();
		 sqlSbf.append(" update SDDCGISPLATFORM.User_Info"
		 		+ " set USER_NAME='"+userName+"',"
		 		+ "DISPLAYNAME='"+displayName+"',"
		 		+ "USER_TYPE='"+userType+"',"
		 		+ "STATUS='"+status+"',"
		 		+ "TELEPHONE='"+phone+"',"
		 		+ "SEX='"+sex+"'"+pwdUpdate+" where user_id='"+userId+"'");
		 //修改用户
		 boolean flag = userDao.executeSql(sqlSbf.toString().replaceAll("'null'", "''"));
		 if(!flag){
			 response.setMsg("修改用户失败");
			 return response;
		 }
		 //用户-组织关系
		 flag= excUserOrg(userId,organizationIds,"update");
		 if(!flag){
			 response.setMsg("修改用户-组织失败");
			 return response;
		 }
		 //用户-角色关系
		 flag= excUserOrle(userId,rolesArr,"update");
		 if(!flag){
			 response.setMsg("修改用户-角色失败");
			 return response;
		 }
		 response.setMsg("操作成功");
		 response.setSuccess(true);
		return response;
	}
	


	private boolean excUserOrle(String userId, String[] rolesArr,String mark) {
		boolean flag  = false;
		if(rolesArr!=null){
			if("update".equals(mark)){
				flag = userDao.executeSql(" delete from SDDCGISPLATFORM.USER_R_ROLE where  user_id = '"+userId+"'");
			}
			for(String roleId : rolesArr){
				 String	  sql = "insert into SDDCGISPLATFORM.USER_R_ROLE(user_id,role_id) values('"+userId+"','"+roleId+"')";
				flag = userDao.executeSql(sql);
			}
		}
		return flag;
	}




	/**
	 * 保存用户-组织关系
	 * 由于USER_ORGANIZATION在报表模块中已经使用,若改表则改动比较麻烦,沿用之前的 -_-
	 * 逻辑: 1.根据传入的用户ID,判断是否新增/编辑
	 *   2.查询出组织表的所有数据,根据传入的组织ID得到对应的部门信息
	 *   3.根据得到的部门类型来判断需要新增/更新那几个字段
	 * 
	 * @param organizationIds
	 * @return
	 */
	private boolean excUserOrg(String userId ,String organizationIds,String flag) {
		if(!StringUtil.isNullOrEmpty(organizationIds)){
			
		 
			String checkSql = "select * from SDDCGISPLATFORM.user_organization where user_id='"+userId+"'";
			String checkData = userDao.querySQL(checkSql);
			
			//判断是否存在
			if ("[{}]".equals(checkData)) {
				flag="add";
			 }
			
			String resultIds = "";
			String selectSql = "select * from SDDCGISPLATFORM.ORGANIZATION ";
			String data = userDao.querySQL(selectSql);
			JSONArray jsonArray = new JSONArray(data);
			if (jsonArray != null && jsonArray.length() > 0) {
				List<Organization> orgList = new ArrayList<Organization>();
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject ret = (JSONObject) jsonArray.get(i);
					Organization temp = new Organization();
					Iterator iterator = ret.keys();
					Map map = new HashMap();
					while (iterator.hasNext()) {
						String key = (String) iterator.next();
						String value = (String) ret.get(key);
						
						switch(key){
							case "ID":temp.setId(value);;break;
							case "ORGANIZATION_TYPE":temp.setOrganizationType(value);break;
							case "PARENT_ID":temp.setParentId(value);break;
							default :break;
						}
						map.put(key, value);
					}
					orgList.add(temp);
				}
				
				Organization temp = null ;
				for(Organization org : orgList){
					if(org.getId().equals(organizationIds)){
						temp = org;
						break;
					}
				}
				
				//集团/公司
				if(temp.getOrganizationType().equals("1")){
					if("add".equals(flag)){
						resultIds+=("values('"+userId+"','"+temp.getId()+"','','')");
					}else if("update".equals(flag)){
						resultIds+=(" set ORGANIZATION_COMPANY_ID='"+temp.getId()+"',ORGANIZATION_BUSINESS_ID='',ORGANIZATION_DEVELOP_ID=''");
					}
					
				}
				
				//事业部
				if(temp.getOrganizationType().equals("2")){
					if("add".equals(flag)){
						resultIds+=("values('"+userId+"','"+temp.getParentId()+"','"+temp.getId()+"','')");
					}else if("update".equals(flag)){
						resultIds+=(" set ORGANIZATION_COMPANY_ID='"+temp.getParentId()+"',ORGANIZATION_BUSINESS_ID='"+temp.getId()+"',ORGANIZATION_DEVELOP_ID=''");
					}
					
				}
				
				
				//拓展组
				if(temp.getOrganizationType().equals("3")){
					if("add".equals(flag)){
						for(Organization org : orgList){
							if(org.getId().equals(temp.getParentId())){
								resultIds+=("values('"+userId+"','"+org.getParentId()+"','"+temp.getParentId()+"','"+temp.getId()+"')");
								break;
							}
						}
					}else if("update".equals(flag)){
						for(Organization org : orgList){
							if(org.getId().equals(temp.getParentId())){
								resultIds+=(" set ORGANIZATION_COMPANY_ID='"+org.getParentId()+"',ORGANIZATION_BUSINESS_ID='"+temp.getParentId()+"',ORGANIZATION_DEVELOP_ID='"+temp.getId()+"'");
								break;
							}
						}
					}

				}
				
				String resultSQL = null;
				if("add".equals(flag)){
					resultSQL = "insert into SDDCGISPLATFORM.USER_ORGANIZATION(USER_ID,ORGANIZATION_COMPANY_ID,ORGANIZATION_BUSINESS_ID,ORGANIZATION_DEVELOP_ID) "+resultIds.toString();

				}else if("update".equals(flag)){
					resultSQL = "update SDDCGISPLATFORM.USER_ORGANIZATION "+resultIds.toString()+" where USER_ID='"+userId+"'";

				} 
				return userDao.executeSql(resultSQL);
				
			}
			
		}
		
		return false;
	}




	public List<Tree> findTree() {
        List<Tree> trees = new ArrayList<Tree>();

        String sql = "select t.id,t.displayname from SDDCGISPLATFORM.USER_INFO t";
        List<UserInfo> res = userDao.queryListSQL(null);
        

      if (res != null && res.size()>0) {
	      for (UserInfo userInfo : res) {
	          Tree treeOne = new Tree();
	
	          treeOne.setId(userInfo.getUserId());
	          treeOne.setText(userInfo.getDisplayname());
 
	          trees.add(treeOne);
	      }
      }
		return trees;
	}




	public Response deleteUserById(String id) {
   	 Response res = new Response();
   	 res.setSuccess(false);
   	 try{
   		UserInfo user = new UserInfo();
   		user.setUserId(id);
    	boolean flag  = userDao.delUserById(user);
    	//TODO 删除人员组织,人员关系
    	String delUserOrg = "delete from sddcgisplatform.user_organization where user_id='"+id+"'";
    	String delUserRole = "delete from sddcgisplatform.user_r_role where user_id='"+id+"'";
    	userDao.executeSql(delUserOrg);
    	userDao.executeSql(delUserRole);
    	 if(flag){
    		 res.setSuccess(true);
    	 }
    	 return res;
   	 }catch(Exception e){
   		 e.printStackTrace();
   		 log.error(e);
   		 res.setMsg("操作失败");
   		 return res;
   	 }
	}




	public Response updatePwd(HttpServletRequest request) {
	   	 Response res = new Response();
	   	 res.setSuccess(false);
		String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
		String userId = request.getParameter("userId");
		userId = userId.replaceAll(" ", "");
		
		//校验原密码
		boolean flag = userDao.checkUserPwd(userId,MD5Util.str2MD5(oldPwd));
		if(!flag){
			res.setMsg("原密码错误");
			return res;
		}
		
		//更新密码
	    flag = userDao.executeSql("update sddcgisplatform.user_info set user_password='"+MD5Util.str2MD5(newPwd)+"' where user_id='"+userId+"'");
		if(flag){
			res.setSuccess(true);
		}
	    
		return res;
	}




	

	 
	
	
	 
}
